package com.atguigu.gmall.seckill.api;

import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.seckill.service.SecKillService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/api/seckill")
@RestController
public class SecKillController {

    @Autowired
    SecKillService secKillService;

    /**
     * 返回当天参与秒杀的所有商品
     *
     * @return
     */
    @GetMapping("/current/goods")
    public List<SeckillGoods> getCurrentSeckillGoods(){
        //查询redis
        List<SeckillGoods> goods  = secKillService.getCurrentSeckillGoodsFromCache();
        if(CollectionUtils.isEmpty(goods)){
            //除非某一刻本地缓存不可用了，可以查redis
            goods = secKillService.getCurrentSeckillGoods();
        }
        return goods;
    }

    @GetMapping("/goods/{skuId}")
    public SeckillGoods getSeckillGoodsDetail(@PathVariable("skuId") Long skuId){
        //拿到所有需要秒杀的商品
//        List<SeckillGoods> seckillGoods = secKillService.getCurrentSeckillGoods();
//
//        //找到当前商品并返回信息。 秒杀商品很多。快速拿到一个指定的秒杀商品
//        SeckillGoods goods = seckillGoods.stream().filter((item) -> {
//            return item.getSkuId().equals(skuId);
//        }).findFirst().get();

        return secKillService.getSeckillGoodsById(skuId);
    }

    @GetMapping("/auth/user/seckillorder")
    public OrderInfo getUserSeckillOrderInfo(HttpServletRequest request) throws JsonProcessingException {
        String userId = AuthContextHolder.getUserId(request);
        return secKillService.getUserSeckillOrderInfo(userId);
    }

}
